package com.fordmotor.service.impl;

import com.alibaba.fastjson.JSON;
import com.fordmotor.pojo.AccessTokenVO;
import com.fordmotor.pojo.GitUser;
import com.fordmotor.service.GitHubService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Primary
@Service
public class GitHubServiceImpl implements GitHubService {



    @Override
    public GitUser authorize(String appid, String token) {
        return null;
    }



    @Override
    public String getAccessToken(AccessTokenVO accessTokenVO) {
        //设置从GitHub那里获取的数据设置成josn格式
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        //通过okhttclient来获取github传过来的用户信息,要利用到AceessTokenDTO内的数据!
        //将传过来的accesstokendto转化为json格式,通过post形式传给github
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenVO));
        Request request = new Request.Builder()
                .url("https://github.com/login/oauth/access_token")
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            //把传过来的token解析
            String token = string.split("&")[0].split("=")[1];
            return token;
        } catch (Exception e) {
            //log.error("getAccessToken error,{}", accessTokenDTO, e);
        }
        return null;
    }

    @Override
    public GitUser getUserInfo(String accessToken) {
        //通过得到的token获取user
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.github.com/user?access_token=" + accessToken)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            //封装
            GitUser githubUser = JSON.parseObject(string, GitUser.class);
            //System.out.println(string);
            return githubUser;
        } catch (Exception e) {
            // log.error("getUser error,{}", accessToken, e);
        }
        return null;
    }
}
